﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Runtime.InteropServices.JavaScript;

namespace apitest.Application.Services
{

    [DynamicApiController]
    public class SynologyService
    {
        string _sid = "";
        string baseUrl = "http://192.168.169.233:5000/webapi/";
        string _userName = "astatech";
        string _password = "Nast!123";
        public SynologyService( )
        {
            
        }

        [HttpGet]
        public async Task<dynamic> Login( )
        {
            HttpClient _httpClient = new();
            var url = $"{baseUrl}auth.cgi?api=SYNO.API.Auth&version=3&method=login&account={_userName}&passwd={_password}&session=FileStation&format=cookie";
            var response = await _httpClient.GetStringAsync(url);
            var res = CheckResult(response);
            JObject obj = JObject.Parse(res);
            _sid = obj["sid"].ToString() ;
            return obj["sid"];
        }

        [HttpGet,QueryParameters]
        public async Task<dynamic> CreateFolder(string path,string folderName)
        {
            await Login();
            HttpClient _httpClient = new();
            var url = $"{baseUrl}entry.cgi?api=SYNO.FileStation.CreateFolder&version=2&method=create&folder_path={path}&name={folderName}&_sid={_sid}";
            var response = await _httpClient.GetStringAsync(url);
            var res = CheckResult(response);
            Console.WriteLine(res);
            JObject obj = JObject.Parse(res);
            return obj ;
        }

        [HttpGet,QueryParameters]
        public async Task<dynamic> ShareFile(string filePath,string sharePassword,DateTime expireDate)
        {
            await Login();
            HttpClient _httpClient = new();
            filePath = "/IT/111/123.txt";
            sharePassword = "123";
            expireDate= DateTime.Now.AddDays(1);
            var url = $"{baseUrl}entry.cgi?api=SYNO.FileStation.Sharing&version=3&method=create&path={filePath}&password={sharePassword}&date_expired={expireDate}&_sid={_sid}";
            var response = await _httpClient.GetStringAsync(url);
            var res = CheckResult(response);
            JObject obj = JObject.Parse(res);
            return obj;
        }

        private string CheckResult(string str)
        {
            var res = JsonConvert.DeserializeObject<SynologyResultClass>(str);
            if (!res.success)
            {
                throw new Exception($"调用失败，错误代码{res.error.code}");
            }
            return res.data.ToString() ;
        }
    }

    public class SynologyResultClass
    {
        public bool success { get; set; }
        public SynologyResultErrorClass error  { get; set; }
        public object data { get; set; }
    }
  public class SynologyResultErrorClass
{
    public int code { get; set; }
}
}
